import axios from 'axios'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { ACCESS_TOKEN, MERCHANT_ID} from "../stores/types";

axios.defaults.timeout = 5000
axios.defaults.baseURL = 'http://192.168.31.212:9090';
axios.defaults.responseType = 'json'

const whiteService = 'login'

const errorHandle = (error) => {
  if (error.response) {
    const data = error.response.data
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if(error.response.status === 500) {
      notification.error({
        message: '服务器异常',
        description: '数据无法获取，请稍后重试。'
      })
    }
  }
  return Promise.reject(error);
}

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  config.headers['authorization'] = ''
  return config;
},errorHandle);

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response.data;
}, errorHandle);

export default axios

export function post(service, data = {}) {
  const merchantId = storage.get(MERCHANT_ID)
  if(merchantId && merchantId > 0) {
    data.merchantId = merchantId
  }
  console.log(data)
  return new Promise((resolve, reject) => {
    axios.post(service,data,{
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'merchantId': merchantId
      }
    }).then(response => {
      resolve(response)
    }).catch(e => {
      reject(e)
    })
  })
}

export function get(service, data = {}) {
  const merchantId = storage.get(MERCHANT_ID)
  if(merchantId && merchantId > 0) {
    data.merchantId = merchantId
  }
  return new Promise((resolve, reject) => {
    axios.get(service,data).then(response => {
      resolve(response)
    }).catch(e => {
      reject(e)
    })
  })
}
